package com.sso;

import java.util.Hashtable;
import java.util.Properties;

import javax.ejb.ActivationConfigProperty;
import javax.ejb.EJB;
import javax.ejb.MessageDriven;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueSender;
import javax.jms.QueueSession;
import javax.jms.TextMessage;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import com.login.LoginRemote;
import com.trust.TrustRemote;




 
/**
 * Message-Driven Bean implementation class for: RBK
 * 
 */
@MessageDriven(mappedName = "SSOQueue", activationConfig = { @ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue") })
public class SSO implements MessageListener {
	QueueConnection cnn = null;
    QueueSender sender = null;
    QueueSession session = null;
    InitialContext ctx;
    Hashtable ht = new Hashtable();
	
    
    //==========
	private void replyToServlet(String message){	
        try {
        	ht.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory");
        	ht.put(Context.PROVIDER_URL,"t3://localhost:7001");

            ctx = new InitialContext(ht);
            Queue queue = (Queue) ctx.lookup("SSOReplyQueue");
            QueueConnectionFactory factory = (QueueConnectionFactory) ctx.lookup("SSOReplyConnectionFactory");
            cnn = factory.createQueueConnection();
            session = cnn.createQueueSession(false, QueueSession.AUTO_ACKNOWLEDGE);
            TextMessage msg = session.createTextMessage();

            msg.setText(message);
            sender = session.createSender(queue);
            sender.send(msg);
            
           
            System.out.println("<sso><replyToServlet>");
            session.close(); // this is important.
        } catch (Exception e) {
            e.printStackTrace();
        }
	}
	//==========
	
	
	@EJB (mappedName="Login")
	LoginRemote login;
	
	@EJB (mappedName="Trust")
	TrustRemote trust;
	
	/**
	 * Default constructor.
	 */
	public SSO() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see MessageListener#onMessage(Message)
	 */
	public void onMessage(Message message) {
		TextMessage tmsg = null;
		tmsg = (TextMessage) message;
		int opCode = 99;
		String parameter1 = null;
		String parameter2 = null;
		
		//parsing message into opcode, and parameters
		String preParse;
		try {
			preParse = tmsg.getText();
			String[] postParse=preParse.split("[|]+");
			opCode=Integer.parseInt(postParse[0]);
			parameter1=postParse[1];
			parameter2=postParse[2];
			
		} catch (JMSException e1) {
			e1.printStackTrace();
		}
		
		switch(opCode){
			case 00: //00 = login
				int pin=0;
				try {
					if(parameter1!=null &&parameter2!=null ){
						try{
							pin = Integer.parseInt(parameter2);
						}catch(Exception x){
							replyToServlet("22||");
							System.out.println("<sso><input is not a integer>");
							break;
						}
						String idPib = parameter1;
					
						System.out.println("parameter 1:"+idPib);
						System.out.println("parameter 2:"+pin);
					
						SSOData ssoData = login(idPib,pin);
						if(ssoData.getLoginSuccess()==false){
							replyToServlet("22||");	//login failed					
						}
						else
						{
							replyToServlet("11|"+idPib+"|"+ssoData.getCookieHash()); // login success with cookie
						}
					}	
			else
						replyToServlet(null);
				} catch (Exception e1) {
					e1.printStackTrace();
					System.out.println("<sso>failed");
				}
				break;
			case 33:
				try {
					boolean checkTrustBoolean = trust.check(parameter1);
					
					if(checkTrustBoolean){
						replyToServlet("44||"); // cookie accepted
					}else{
						replyToServlet("55||"); //cookie expired
					}
					
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				break;
			case 99:
				System.out.println("<sso><preparse>failed");
				break;
			}
		
	}
	
	private SSOData login(String idPib, int pin) throws Exception{
		SSOData ssoData = new SSOData();
		Boolean loginBoolean = login.login(idPib, pin);
		if(loginBoolean==true){
			String cookieHash = trust.newLogin(idPib);
			ssoData.setCookieHash(cookieHash);			
		}
		
		return ssoData;
	}

	private boolean checkTrust(String cookieHash) throws Exception{
		return trust.check(cookieHash);
		
	}
	
}
